const log4js = require('../../../../utils/logUtils');
const logger = log4js.getLogger('sip');
const sip = require("sip");
const deviceCache = require("../../../../db/deviceCache");
const fs = require("fs");
const path = require('path');
const moment = require('moment');
const sipUtils = require("../../../../utils/sipUtils");
const config = require("../../../../db/config");
const clientUtils = require("../clientUtils");
const settingModel = require("../../../../model/setting");

const TAG = "[recordHandler]";
module.exports = {
    async handle(req, content) {
        // 传的DeviceID 实际是channelId
        const channelId = content.Query.DeviceID;
        const startTime = content.Query.StartTime;
        const endTime = content.Query.EndTime;
        const {upwardUri, upward } = await clientUtils.generateClientParams();
        // 处理录像信息
        sip.send(sip.makeResponse(req, 200, 'OK'));

        const fileList = await this.getRecordList(channelId, startTime, endTime);
        logger.info(TAG, 'fileList=', fileList);
        // 要生成格式
        const xml = this.getResponseXml(channelId, fileList);
        sip.send({
            method: 'MESSAGE', uri: upwardUri, version: config.sip.version,
            headers: {
                from: {uri: deviceCache.localUri, params: {tag:sipUtils.rstring()}},
                to: {uri: deviceCache.localUri},
                'call-id': sipUtils.rstring(),
                cseq: req.headers.cseq,
                'Content-Type': 'Application/MANSCDP+xml',
                'expires': '3600',
                'Max-Forwards': 70
            },
            content: '<?xml version="1.0" encoding="GB2312" ?>' +
                '<Response>' +
                '<CmdType>RecordInfo</CmdType>' +
                '<SN>' + content.Query.SN + '</SN>' +
                '<DeviceID>' + upward.self_account + '</DeviceID>' +
                '<Name>' + channelId + '</Name>' +
                '<SumNum>' + 1 + '</SumNum>' +
                '<RecordList Num="' + 1 + '">' +
                xml +
                '</RecordList></Response>'
        }, function (ret) {
             logger.info(ret);

        });

    },
    getResponseXml(deviceId, fileList) {
        // 遍历fileList
        let str = '';
        fileList.forEach((item,k) => {
            str += '<Item>' +
                '<DeviceID>' + deviceId + '</DeviceID>' +
                '<Name>' + deviceId + '</Name>' +
                '<FilePath>' + item.FilePath + '</FilePath>' +
                '<Address></Address>' +
                '<StartTime>' + item.StartTime + '</StartTime>' +
                '<EndTime>' + item.EndTime + '</EndTime>' +
                '<Secrecy>0</Secrecy>' +
                '<Type>time</Type>' +
                '</Item>';
        });
        return str;
    },
    // 从 deviceCache.record.path目录位置读取指定时间段的文件列表

    async getRecordList(channelId, startTime, endTime) {
        const settings =await settingModel.load();
        settings.record = settings.record || {};

        const deviceId = settings.sip_command_account;

        const startDate = moment(startTime);
        const formattedStartDate = startDate.format('YYYY-MM-DD');
        const relativePath = `${deviceId}_${channelId}/${formattedStartDate}`;
        let recordPath = `${config.record.path}/mp4/record/proxy/${relativePath}`;

        const fileList = [];
        const files = fs.readdirSync(recordPath);
        files.forEach((file) => {
            const filePath = path.join(recordPath, file);
            const stats = fs.statSync(filePath);

            if (stats.isFile() ) {
            // 获取文件大小
                const fileSizeInBytes = stats.size;
                if(fileSizeInBytes) {
                    const parseFile = path.parse(file);
                    const fileName = parseFile.name;

                    const array = fileName.split('_');
                    const startInFile = array[0];
                    const endInFile = array[1];
                    const durationInFile = array[2];
                    const fileSizeInFile = array[3];
                    const startTimeInFile = moment(startInFile, 'YYYYMMDD-HHmmss');
                    const endTimeInFile = moment(endInFile, 'YYYYMMDD-HHmmss');

                    if (startTimeInFile.isBetween(startDate, moment(endTime) ||
                        endTimeInFile.isBetween(startDate, moment(endTime)))) {
                        // 格式化开始时间
                        const formattedStartTime = startTimeInFile.format('YYYY-M-DTH:m:s');

                        // 格式化结束时间（加1小时，减1秒）
                        const formattedEndTime = endTimeInFile.format('YYYY-M-DTH:m:s');

                        fileList.push({
                            Name: channelId,
                            FilePath: `${relativePath}/${fileName}${parseFile.ext}`,
                            Address: '',
                            StartTime: formattedStartTime,
                            EndTime: formattedEndTime,
                            Secrecy: 0,
                            Type: 'time',
                            Size: fileSizeInFile,
                            Duration: durationInFile
                        });
                    }
                }
            }
        });

        return fileList;
    }
}
